package ev.dao;
import ev.traffic.Path;
import java.sql.*;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
public class IDAOImpl implements IDAO {
		private Connection conn = null;
		public IDAOImpl(Connection conn){
				this.conn = conn;
		}
		public List<Integer> findPathByNodes(int start,int end){
				int result = 0;
				List<Integer> roadLine = new ArrayList<Integer>();
				PreparedStatement pstmt = null;
				String sql = "SELECT startpoint,roadLine,length,endpoint FROM data where startpoint like ? and endpoint like ?";
				try{
						pstmt = this.conn.prepareStatement(sql);
						pstmt.setInt(1,start);
						pstmt.setInt(2,end);
						ResultSet rs = pstmt.executeQuery();
						if(rs.next()){
								String line = rs.getString(2);
								List<String> temp = Arrays.asList(line.split(","));
								for(String s:temp){
										roadLine.add(new Integer(s.trim()));
								}
						}
						rs.close();
				}catch(Exception e){
						e.printStackTrace();
				}finally{
						if(pstmt != null){
								try{
									pstmt.close();
								}catch(Exception e1){
										e1.printStackTrace();
								}
						}
				}
				return roadLine;
		}
		public List<Path> findAll(int start){
				List<Path> pathList = new ArrayList<Path>();
				PreparedStatement pstmt = null;
				String sql = "SELECT startpoint,roadLine,length,endpoint FROM data where startpoint like ?";
				try{
						pstmt = this.conn.prepareStatement(sql);
						pstmt.setInt(1,start);
						ResultSet rs = pstmt.executeQuery();
						if(rs.next()){
								Path path = new Path();
								path.setStart(start);
								path.setEnd(rs.getInt(2));
								path.setLength(rs.getInt(4));
								pathList.add(path);
						}
						rs.close();
				}catch(Exception e){
						e.printStackTrace();
				}finally{
						if(pstmt != null){
								try{
									pstmt.close();
								}catch(Exception e1){
										e1.printStackTrace();
								}
						}
				}
				return pathList;
		}
		public int findLengthByNodes (int start,int end){
				int result = 0;
				PreparedStatement pstmt = null;
				String sql = "SELECT startpoint,roadLine,length,endpoint FROM data where startpoint like ? and endpoint like ?";
				try{
						pstmt = this.conn.prepareStatement(sql);
						pstmt.setInt(1,start);
						pstmt.setInt(2,end);
						ResultSet rs = pstmt.executeQuery();
						if(rs.next()){
								result = Integer.parseInt(rs.getString(3));
						}
						rs.close();
				}catch(Exception e){
						e.printStackTrace();
				}finally{
						if(pstmt != null){
								try{
									pstmt.close();
								}catch(Exception e1){
										e1.printStackTrace();
								}
						}
				}
				return result;
		}
}
